//
//  DetailView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/7.
//

import SwiftUI
import TLCLock

class SheetModel: Identifiable {}

struct DetailView: View {
    
    let mac: String

    @State private var sheetModel: SheetModel?
    
    @State var isConnected: Bool = false

    var body: some View {
        VStack(spacing: 10) {
            Text(device.macAddress)
                .bold()
                .foregroundColor(.orange)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
            
            Text(isConnected ? "已连接": "未连接")
                .bold()
                .foregroundColor(.primary)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
                .onReceive(device.getConnectPublisher(), perform: { value in
                    isConnected = value
                })
            
            YxrActionView(
                data: [
                    (0, "连接"),
                    (4, "断开连接"),
                    (1, "锁信息"),
                    (5, "授时"),
                    (3, "开锁"),
                ], column: 3,
                itemBuilder: { value in
                    YXRActionItem(text: value.1) {
                        switch value.0 {
                        case 0: connectDevice()
                        case 1: getRomInfo()
                        case 3: openLock()
                        case 4: disconnectDevice()
                        case 5: fixTime()
                        default:
                            print("未实现的方法")
                        }
                    }
                }
            )
            .padding(.horizontal, 10)
            
            YxrActionView(
                data: [
                    (11, "添加蓝牙管理员"),
                    (7, "密码"),
                    (8, "指纹"),
                    (6, "卡"),
                    (5, "锁升级"),
                    (9, "其他"),
                ],
                itemBuilder: { value in
                    NavigationLink(
                        destination: {
                            switch value.0 {
                            case 5: DFUView(model: DFUModel(device: device))
                            case 6: CardView(model: CardModel(device: device))
                            case 7: PwdView(model: PwdModel(device: device))
                            case 8: FpView(model: FpModel(device: device))
                            case 9: OtherView(model: OtherModel(device: device))
                            case 11: InitLockView(device: device)
                            default: EmptyView()
                            }
                        },
                        label: {
                            Text(value.1)
                                .font(.system(size: 14.0))
                                .foregroundColor(.white)
                                .frame(minWidth: 40, maxWidth: .infinity, minHeight: 49, maxHeight: 49)
                                .background(Color.accentColor)
                                .cornerRadius(10)
                        }
                    )
                }
            )
            .padding(.horizontal, 10)
            
            LogView()
        }
        .sheet(item: $sheetModel) { identifier in
            if let infoModel = identifier as? InfoModel {
                InfoView(model: infoModel)
            }
        }.onAppear {
            device.prewarm()
        }
    }
}

extension DetailView {
    var device: LockDevice {
        return TLCManager.getLockDevice(mac: mac, featureCode: Server.testFeatureCode)
    }

    func connectDevice() {
        Log.info("点击了连接")
        Task {
            showLoading()
            let result = await device.connectDevice()
            hideLoading()
            if result.isFailure {
                showToast(result.errorMessage)
                return
            }

            showToast("已连接")
        }
    }

    func disconnectDevice() {
        device.disconnectDevice()
    }

    func fixTime() {
        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        lockTask(desc: "授时") {
            await device.asyncTime(serverDate: Server.now(), lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func getRomInfo() {
        Log.info("get rom info.......")

        Task {
            showLoading()
            let result = await device.getLockInfo()
            hideLoading()

            if result.isFailure {
                showToast(result.errorMessage)
                return
            }

            sheetModel = InfoModel(info: result.value!)
        }
    }

    func openLock() {
        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("无lockKey")
            return
        }
        lockTask(desc: "开锁") {
            let result = await device.openLock(serverDate: Server.now(), lockKey: lockKey, trackId: Server.testTrackId)
            if result.isSuccess {
                let value = result.value!
                if let voltage = value.voltage {
                    Log.info("voltage: \(voltage)")
                }
                
                if let powerPercent = value.powerPercent {
                    Log.info("powerPercent: \(powerPercent)")
                }
            }
            return result
        }
    }
}
